package fu.k4c.vTeam.Main;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import fu.k4c.vTeam.R;
import fu.k4c.vTeam.Login.LoginActivity;
import fu.k4c.vTeam.Manage.CreatePlaceActivity;
import fu.k4c.vTeam.Object.ItemViewPlace;
import fu.k4c.vTeam.Object.PlaceDetails;
import fu.k4c.vTeam.ViewDetails.PlaceTabLayoutActivity;

public class ViewPlaceActivity extends BaseActivity {
	String categories;
	String status;
	String email = "";
	String city = "";
	String cateput;
	String pID;
	List<ItemViewPlace> yourClassList;
	EditText et_search;
	int textlength = 0;
	int page = 1;
	int nextPage=1;
	boolean loading = false;
	int categoriesAction = 1;
	int cityAction = 1;
	ProgressDialog proDialog;
	static final private int CHOOSE_ADD = 1;
	int CURRENT_TAG = 0;
	static final int TAG_GUEST = 0;
	static final int TAG_USER = 1;
	GridView gv_categories;
	Spinner Cityspinner;
	Spinner CateSpinner;
	private DisplayImageOptions options;
	boolean isFirst = false;
	ListCategoriesView adapter;
	String cities[] = { "Tất cả", "Hà Nội", "TP Hồ Chí Minh", "Khác" };
	String cate[] = { "Ẩm thực", "Bệnh viện", "Cà phê", "Mua sắm", "Trạm xăng",
			"Giải trí", "ATM" };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.view_categories_activity);
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.stub_image)
				.showImageForEmptyUri(R.drawable.image_for_empty_url)
				.cacheInMemory().cacheOnDisc()
				.displayer(new RoundedBitmapDisplayer(20)).build();
		proDialog = ProgressDialog.show(ViewPlaceActivity.this, "",
				"Đang tải dữ liệu...");
		new Thread() {
			public void run() {

				try {
					sleep(1000);

				} catch (Exception e) {
					System.out.print(e.toString());
				}
				// dismiss the progressdialog
				proDialog.dismiss();
			}
		}.start();
		gv_categories = (GridView) findViewById(R.id.gv_categories_activity);
		gv_categories.setOnScrollListener(new onLoadScrollListener());
		CateSpinner = (Spinner) findViewById(R.id.sp_view_categories);
		Bundle data = getIntent().getExtras();
		try {
			if (data != null) {
				categories = data.getString("CategorieName");
				status = data.getString("status");
				email = data.getString("email");
				city = "4";
				cateput = data.getString("Category");
				getData(categories, city);
			}
			if (status.equals("True")) {
				CURRENT_TAG = TAG_USER;
			} else {
				CURRENT_TAG = TAG_GUEST;
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			Toast.makeText(getApplicationContext(), e.toString(),
					Toast.LENGTH_LONG).show();
		}

		Button btn_create_place = (Button) findViewById(R.id.btn_view_categories_createPlace);
		btn_create_place.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub

				if (CURRENT_TAG == TAG_USER) {
					Intent i = new Intent(ViewPlaceActivity.this,
							CreatePlaceActivity.class);
					i.putExtra("email", email);
					startActivityForResult(i, CHOOSE_ADD);
				} else {
					Toast.makeText(getApplicationContext(),
							"Vui lòng đăng nhập để sử dụng chức năng này",
							Toast.LENGTH_LONG).show();
				}
			}
		});
		Button btn_back = (Button) findViewById(R.id.btn_view_categories_back);
		btn_back.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});

		ArrayAdapter<String> spinnerArrayAdapter2 = new ArrayAdapter<String>(
				this, android.R.layout.simple_spinner_item, cate);
		spinnerArrayAdapter2
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The
																							// drop
																							// down
																							// vieww
		CateSpinner.setAdapter(spinnerArrayAdapter2);
		CateSpinner.setSelection(getIndex(CateSpinner, cateput));
		CateSpinner
				.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent,
							View view, int pos, long id) {
						if (categoriesAction > 1) {
							proDialog = ProgressDialog.show(
									ViewPlaceActivity.this, "",
									"Đang tải dữ liệu...");
							new Thread() {
								public void run() {

									try {
										sleep(1000);

									} catch (Exception e) {
										System.out.print(e.toString());
									}
									// dismiss the progressdialog
									proDialog.dismiss();
								}
							}.start();

							page = 1;
							nextPage = 1;
							Object item = parent.getItemAtPosition(pos);
							String catechoise = item.toString();
							if (catechoise.equals("Ẩm thực")) {
								categories = "amthuc";
								getData(categories, city);
							} else if (catechoise.equals("Bệnh viện")) {
								categories = "benhvien";
								getData(categories, city);
							} else if (catechoise.equals("Cà phê")) {
								categories = "cafe";
								getData(categories, city);

							} else if (catechoise.equals("Mua sắm")) {
								categories = "shopping";
								getData(categories, city);
							} else if (catechoise.equals("Trạm xăng")) {
								categories = "tramxang";
								getData(categories, city);
							} else if (catechoise.equals("Giải trí")) {
								categories = "giaitri";
								getData(categories, city);
							} else if (catechoise.equals("ATM")) {
								categories = "atm";
								getData(categories, city);
							}
						}
						categoriesAction++;

					}

					public void onNothingSelected(AdapterView<?> parent) {

						// }
					}
				});
		Cityspinner = (Spinner) findViewById(R.id.sp_view_categories_povide);
		ArrayAdapter<String> spinnerArrayAdapter1 = new ArrayAdapter<String>(
				this, android.R.layout.simple_spinner_item, cities);
		spinnerArrayAdapter1
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The
																							// drop
																							// down
																							// vieww
		Cityspinner.setAdapter(spinnerArrayAdapter1);
		Cityspinner
				.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent,
							View view, int pos, long id) {
						if (cityAction > 1) {
							proDialog = ProgressDialog.show(
									ViewPlaceActivity.this, "",
									"Đang tải dữ liệu...");
							new Thread() {
								public void run() {

									try {
										sleep(1000);

									} catch (Exception e) {
										System.out.print(e.toString());
									}
									// dismiss the progressdialog
									proDialog.dismiss();
								}
							}.start();
							page = 1;
							nextPage = 1;
							Object item = parent.getItemAtPosition(pos);
							String mcity = item.toString();
							if (mcity.equals("Hà Nội")) {
								city = "1";
								getData(categories, city);
							} else if (mcity.equals("TP Hồ Chí Minh")) {
								city = "2";
								getData(categories, city);
							} else if (mcity.equals("Khác")) {
								city = "3";
								getData(categories, city);
							} else {
								city = "4";
								getData(categories, city);
							}
						}
						cityAction++;

					}

					public void onNothingSelected(AdapterView<?> parent) {
					}
				});
		Button btn_like = (Button) findViewById(R.id.btn_view_categories_like);
		btn_like.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (CURRENT_TAG == TAG_USER) {
					Intent i = new Intent(ViewPlaceActivity.this,
							FavoritesActivity.class);
					i.putExtra("email", email);
					i.putExtra("status", status);
					startActivity(i);
				} else {
					Toast.makeText(getApplicationContext(),
							"Vui lòng đăng nhập để sử dụng chức năng này",
							Toast.LENGTH_LONG).show();
				}
			}
		});
		Button btn_manager = (Button) findViewById(R.id.btn_view_categories_manager);
		btn_manager.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (CURRENT_TAG == TAG_USER) {
					Intent i = new Intent(ViewPlaceActivity.this,
							ViewManagerActivity.class);
					i.putExtra("email", email);
					startActivity(i);
				} else {

					Toast.makeText(getApplicationContext(),
							"Vui lòng đăng nhập để sử dụng chức năng này",
							Toast.LENGTH_LONG).show();
				}
			}
		});
		et_search = (EditText) findViewById(R.id.et_view_categories_search);
		et_search.addTextChangedListener(new TextWatcher() {

			public void onTextChanged(CharSequence cs, int arg1, int arg2,
					int arg3) {
				// When user changed the Text
				textlength = et_search.getText().length();
				final List<ItemViewPlace> listSearch = new ArrayList<ItemViewPlace>();
				;
				for (int i = 0; i < yourClassList.size(); i++) {
					if (yourClassList.get(i).getName().toLowerCase()
							.indexOf(et_search.getText().toString()) >= 0
							|| yourClassList.get(i).getAddress().toLowerCase()
									.indexOf(et_search.getText().toString()) >= 0) {
						listSearch.add(yourClassList.get(i));
					}
				}
				ListCategoriesView adapter = new ListCategoriesView(
						ViewPlaceActivity.this, listSearch);
				gv_categories.setAdapter(adapter);
				gv_categories.setOnItemClickListener(new OnItemClickListener() {
					public void onItemClick(AdapterView<?> arg0, View v,
							int position, long id) {
						proDialog = ProgressDialog.show(ViewPlaceActivity.this,
								"", "Đang tải dữ liệu...");
						new Thread() {
							public void run() {

								try {
									sleep(2000);

								} catch (Exception e) {
									System.out.print(e.toString());
								}
								// dismiss the progressdialog
								proDialog.dismiss();
							}
						}.start();
						SchemeRegistry registry = new SchemeRegistry();
						registry.register(new Scheme("http", PlainSocketFactory
								.getSocketFactory(), 80));
						HttpParams httpParams = new BasicHttpParams();
						ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(
								httpParams, registry);
						HttpClient client = new DefaultHttpClient(connMgr,
								httpParams);
						HttpPost post = new HttpPost(
								getString(R.string.connectionString)
										+ "vLocationService/GetDetailLocation");
						post.setHeader("Accept", "application/json");
						post.setHeader("Content-type", "application/json");
						HashMap<String, Object> postParameters = new HashMap<String, Object>();
						postParameters.put("IDofItemRevision",
								listSearch.get(position).getIdPlace());
						postParameters.put("username", email);
						// Toast.makeText(getApplicationContext(),"ID la :"+yourClassList.get(position).getIdPlace(),
						// Toast.LENGTH_LONG).show();

						Gson gson = new Gson();
						try {
							String jsonParameters = gson.toJson(postParameters);
							post.setEntity(new StringEntity(jsonParameters));
							HttpResponse response = client.execute(post);
							HttpEntity entity = response.getEntity();
							String jsonresult = EntityUtils.toString(entity);
							PlaceDetails mDetails = gson.fromJson(jsonresult,
									PlaceDetails.class);
							Intent i = new Intent(ViewPlaceActivity.this,
									PlaceTabLayoutActivity.class);
							// Toast.makeText(getApplicationContext(),""+mDetails.isReLike(),
							// Toast.LENGTH_LONG).show();
							i.putExtra("address", ""
									+ listSearch.get(position).getAddress());
							i.putExtra("placename", mDetails.getReName());
							i.putExtra("placetel", mDetails.getRePhone());
							i.putExtra("likenumber", mDetails.getReslVote());
							i.putExtra("visitnumber", mDetails.getReslVisit());
							i.putExtra("createby", mDetails.getReCreatBy());
							i.putExtra("des", mDetails.getReDescription());
							i.putExtra("lat", mDetails.getRelat());
							i.putExtra("long", mDetails.getRelong());
							i.putExtra("visit", mDetails.isReDaDen());
							i.putExtra("like", mDetails.isReLike());
							i.putExtra("IDofItemRevision",
									listSearch.get(position).getIdPlace());
							i.putExtra("views",
									"" + mDetails.getSolgnguoiview());
							i.putExtra("createbyemail",
									"" + mDetails.getEmail());
							if (CURRENT_TAG == TAG_USER) {
								i.putExtra("username", email);
							} else {
								i.putExtra("username", "Guest");
							}
							startActivity(i);
							// i.putExtra("linkanh",image);
							// Toast.makeText(getApplicationContext(),mDetails.getRelat()+", "+mDetails.getRelong(),
							// Toast.LENGTH_LONG).show();
						} catch (Exception e) {
							// TODO: handle exception
							Toast.makeText(getApplicationContext(),
									"Không kết nối được máy chủ!",
									Toast.LENGTH_LONG).show();
						}

					}
				});
			}

			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub

			}

			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		Bundle info = new Bundle();
		info = data.getExtras();
		if (resultCode == RESULT_OK && requestCode == CHOOSE_ADD) {
			proDialog = ProgressDialog.show(ViewPlaceActivity.this, "",
					"Đang tải dữ liệu...");
			new Thread() {
				public void run() {

					try {
						sleep(1500);

					} catch (Exception e) {

					}
					// dismiss the progressdialog
					proDialog.dismiss();
				}
			}.start();
			getData(categories, city);
		}
		if (requestCode == RESULT_CANCELED) {

		}
	}

	private void getData(String cate, String ID) {
		// TODO Auto-generated method stub
		try {
			pID = ID;
			SchemeRegistry registry = new SchemeRegistry();
			registry.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));
			HttpParams httpParams = new BasicHttpParams();
			ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(
					httpParams, registry);
			HttpClient client = new DefaultHttpClient(connMgr, httpParams);
			HttpPost post = new HttpPost(getString(R.string.connectionString)
					+ "vLocationService/GetPlacelinformation");
			post.setHeader("Accept", "application/json");
			post.setHeader("Content-type", "application/json");
			HashMap<String, Object> postParameters = new HashMap<String, Object>();
			postParameters.put("CategorieName", cate);
			postParameters.put("CityID", ID);
			postParameters.put("Page", ""+page);
			Gson gson = new Gson();
			String jsonParameters = gson.toJson(postParameters);
			post.setEntity(new StringEntity(jsonParameters));
			HttpResponse response = client.execute(post);

			HttpEntity entity = response.getEntity();
			String jsonresult = EntityUtils.toString(entity);

			try {
				Type listType = new TypeToken<ArrayList<ItemViewPlace>>() {
				}.getType();
				// yourClassList.clear();
				yourClassList = new Gson().fromJson(jsonresult, listType);
				nextPage = Integer.parseInt(yourClassList.get(0).getPage());
				Log.i("nextPage1", ""+nextPage);
				if (yourClassList.size() == 0) {
					Toast.makeText(getApplicationContext(),
							"Không có kết quả nào", Toast.LENGTH_LONG).show();
				}
				adapter = new ListCategoriesView(this,
						yourClassList);
				gv_categories.setAdapter(adapter);
				gv_categories.setOnItemClickListener(new OnItemClickListener() {
					public void onItemClick(AdapterView<?> arg0, View v,
							int position, long id) {
						proDialog = ProgressDialog.show(ViewPlaceActivity.this,
								"", "Đang tải dữ liệu...");
						new Thread() {
							public void run() {

								try {
									sleep(2000);

								} catch (Exception e) {
									System.out.print(e.toString());
								}
								// dismiss the progressdialog
								proDialog.dismiss();
							}
						}.start();
						SchemeRegistry registry = new SchemeRegistry();
						registry.register(new Scheme("http", PlainSocketFactory
								.getSocketFactory(), 80));
						HttpParams httpParams = new BasicHttpParams();
						ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(
								httpParams, registry);
						HttpClient client = new DefaultHttpClient(connMgr,
								httpParams);
						HttpPost post = new HttpPost(
								getString(R.string.connectionString)
										+ "vLocationService/GetDetailLocation");
						post.setHeader("Accept", "application/json");
						post.setHeader("Content-type", "application/json");
						HashMap<String, Object> postParameters = new HashMap<String, Object>();
						postParameters.put("IDofItemRevision", yourClassList
								.get(position).getIdPlace());
						postParameters.put("username", email);
						// Toast.makeText(getApplicationContext(),"ID la :"+yourClassList.get(position).getIdPlace(),
						// Toast.LENGTH_LONG).show();

						Gson gson = new Gson();
						try {
							String jsonParameters = gson.toJson(postParameters);
							post.setEntity(new StringEntity(jsonParameters));
							HttpResponse response = client.execute(post);
							HttpEntity entity = response.getEntity();
							String jsonresult = EntityUtils.toString(entity);
							PlaceDetails mDetails = gson.fromJson(jsonresult,
									PlaceDetails.class);
							Intent i = new Intent(ViewPlaceActivity.this,
									PlaceTabLayoutActivity.class);
							// Toast.makeText(getApplicationContext(),""+mDetails.isReLike(),
							// Toast.LENGTH_LONG).show();
							i.putExtra("address",
									""
											+ yourClassList.get(position)
													.getAddress());
							i.putExtra("placename", mDetails.getReName());
							i.putExtra("placetel", mDetails.getRePhone());
							i.putExtra("likenumber", mDetails.getReslVote());
							i.putExtra("visitnumber", mDetails.getReslVisit());
							i.putExtra("createby", mDetails.getReCreatBy());
							i.putExtra("des", mDetails.getReDescription());
							i.putExtra("lat", mDetails.getRelat());
							i.putExtra("long", mDetails.getRelong());
							i.putExtra("visit", mDetails.isReDaDen());
							i.putExtra("like", mDetails.isReLike());
							i.putExtra("IDofItemRevision",
									yourClassList.get(position).getIdPlace());
							i.putExtra("views",
									"" + mDetails.getSolgnguoiview());
							i.putExtra("createbyemail",
									"" + mDetails.getEmail());
							if (CURRENT_TAG == TAG_USER) {
								i.putExtra("username", email);
							} else {
								i.putExtra("username", "Guest");
							}
							startActivity(i);
							// i.putExtra("linkanh",image);
							// Toast.makeText(getApplicationContext(),mDetails.getRelat()+", "+mDetails.getRelong(),
							// Toast.LENGTH_LONG).show();
						} catch (Exception e) {
							// TODO: handle exception
							Toast.makeText(getApplicationContext(),
									"Không kết nối được máy chủ!",
									Toast.LENGTH_LONG).show();
						}

					}
				});
			} catch (Exception e) {
				Toast.makeText(getApplicationContext(),
						"Không kết nối được máy chủ!", Toast.LENGTH_LONG)
						.show();
				// TODO: handle exception
			}
		} catch (Exception e) {
			// TODO: handle exception
			Toast.makeText(
					getApplicationContext(),
					"Bạn vui lòng kiểm tra lại kết nối Internet "
							+ e.toString(), Toast.LENGTH_LONG).show();
		}

	}

	private int getIndex(Spinner spinner, String myString) {

		int index = 0;

		for (int i = 0; i < spinner.getCount(); i++) {
			if (spinner.getItemAtPosition(i).equals(myString)) {
				index = i;
			}
		}
		return index;
	}
	public class onLoadScrollListener implements OnScrollListener {
		int lastinScreen;
		int currentScrollState;
		public onLoadScrollListener() {
	     }
	     public onLoadScrollListener(int lastinScreen) {
	         this.lastinScreen = lastinScreen;
	     }
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// TODO Auto-generated method stub
			lastinScreen = firstVisibleItem + visibleItemCount;
			Log.i("scroll", "lastinScreen  :"+ lastinScreen);
			Log.d("scroll", "totalItemCount  :"+ totalItemCount);
			if (!loading && (lastinScreen==totalItemCount) && nextPage >=2 && totalItemCount>0){
				page = nextPage;
				Log.d("scroll", "page  :"+ page);
				new loadMoreList().execute();
			}
		}

		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub
			this.currentScrollState = scrollState;
		}
		
	}
	public class loadMoreList extends AsyncTask<Void, Void, Void>{
		String e="";
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			loading = true;
			Log.i("onPre", "da chay vao onPre");
			proDialog = new ProgressDialog(ViewPlaceActivity.this);
			proDialog.setMessage("Đang kết nối đến máy chủ...");
			proDialog.setCancelable(false);
			proDialog.show();
			super.onPreExecute();
		}
		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
					try {
						SchemeRegistry registry = new SchemeRegistry();
						registry.register(new Scheme("http", PlainSocketFactory
								.getSocketFactory(), 80));
						HttpParams httpParams = new BasicHttpParams();
						ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(
								httpParams, registry);
						HttpClient client = new DefaultHttpClient(connMgr, httpParams);
						HttpPost post = new HttpPost(getString(R.string.connectionString)
								+ "vLocationService/GetPlacelinformation");
						post.setHeader("Accept", "application/json");
						post.setHeader("Content-type", "application/json");
						HashMap<String, Object> postParameters = new HashMap<String, Object>();
						postParameters.put("CategorieName", categories);
						postParameters.put("CityID", pID);
						postParameters.put("Page", ""+page);
						Gson gson = new Gson();
						String jsonParameters = gson.toJson(postParameters);
						e = jsonParameters;
						post.setEntity(new StringEntity(jsonParameters));
						HttpResponse response = client.execute(post);
						HttpEntity entity = response.getEntity();
						String jsonresult = EntityUtils.toString(entity);
						Type listType = new TypeToken<ArrayList<ItemViewPlace>>() {
						}.getType();
						// yourClassList.clear();
						List<ItemViewPlace> yourClassList2 = new Gson().fromJson(jsonresult, listType);
						nextPage = Integer.parseInt(yourClassList2.get(0).getPage());
						Log.i("nextPage2", ""+nextPage);
						for(int i = 0; i<=yourClassList2.size();i++)
						{
							yourClassList.add(yourClassList2.get(i));
						}
					} catch (Exception e) {
						// TODO: handle exception
//						this.e=e.toString(); 
					}
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			proDialog.dismiss();
			adapter.notifyDataSetChanged();
			loading = false;
//			Toast.makeText(getApplicationContext(), e, Toast.LENGTH_LONG).show();
			super.onPostExecute(result);
		}
		
	}
	public class ListCategoriesView extends BaseAdapter {
		Activity ListCategoriesView;
		List<ItemViewPlace> data;
		LayoutInflater inflater = null;

		private class ViewHolder {
			public TextView tv_name;
			public TextView tv_phone;
			public TextView tv_address;
			public TextView tv_view;
			public ImageView imv_avatar;
		}

		public ListCategoriesView(Activity mListCategoriesView,
				List<ItemViewPlace> mdata) {
			ListCategoriesView = mListCategoriesView;
			data = mdata;

		}

		public int getCount() {
			// TODO Auto-generated method stub
			return data.size();
		}

		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return data.get(position);
		}

		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		public View getView(int position, View convertView, ViewGroup arg2) {
			// TODO Auto-generated method stub
			View view = convertView;
			final ViewHolder holder;
			if (convertView == null) {
				view = getLayoutInflater().inflate(
						R.layout.row_view_by_categories, null);
				holder = new ViewHolder();
				holder.imv_avatar = (ImageView) view
						.findViewById(R.id.imv_row_view);
				holder.tv_name = (TextView) view
						.findViewById(R.id.tv_row_view_name);
				holder.tv_phone = (TextView) view
						.findViewById(R.id.tv_row_view_phone);
				holder.tv_address = (TextView) view
						.findViewById(R.id.tv_row_view_address);
				holder.tv_view = (TextView) view
						.findViewById(R.id.tv_row_view_views);
				view.setTag(holder);
			} else
				holder = (ViewHolder) view.getTag();

			String imageurl;
			if (data.get(position).getAvatar() != null) {
				if (data.get(position).getAvatar().toLowerCase()
						.indexOf("http://") >= 0) {
					imageurl = data.get(position).getAvatar();

				} else {
					imageurl = getString(R.string.connectionString)
							+ data.get(position).getAvatar();
				}
			} else {
				imageurl = data.get(position).getAvatar();
			}
			imageLoader.init(ImageLoaderConfiguration
					.createDefault(getBaseContext()));
			// imageLoader.displayImage(data.get(position).getAvatar(),
			// holder.imv_avatar, options);
			imageLoader.displayImage(imageurl, holder.imv_avatar, options,
					new SimpleImageLoadingListener() {
						@Override
						public void onLoadingComplete(Bitmap loadedImage) {
							Animation anim = AnimationUtils.loadAnimation(
									ViewPlaceActivity.this, R.anim.fade_in);
							holder.imv_avatar.setAnimation(anim);
							anim.start();
						}
					});

			holder.tv_name.setText(data.get(position).getName());
			if (data.get(position).getPhone() == null) {
				holder.tv_phone.setText("Số điện thoại : N\\A");
			} else
				holder.tv_phone.setText("Số điện thoại : "
						+ data.get(position).getPhone());
			holder.tv_address.setText("Địa chỉ : "
					+ data.get(position).getAddress());
			holder.tv_view.setText("Lượt xem : "
					+ data.get(position).getViews());
			return view;
		}

	}

}
